package com.hkd.Dao模式.util;

import java.sql.*;

/**
 * @author ：陈奕安（3048279304@qq.com）
 * @date ：Created in 2025/5/28 10:58
 * @description：
 * @modified By：
 * @version:
 */
public class DateBase2 {
    static  String url="jdbc:mysql://localhost:3306/bookstore";
    static String user="root";
    static String password="root";
    static String driverClass="com.mysql.cj.jdbc.Driver";
    protected Connection con=null;
    protected PreparedStatement ps=null;
    protected ResultSet rs=null;
    static {
        try{
            Class.forName(driverClass);
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }

    }
    public Connection getConnection(){
        try {
            if (con==null||con.isClosed())
                con= DriverManager.getConnection(url,user,password);
        }catch (SQLException e){
            e.printStackTrace();
        }
        return con;
    }
    public int executeUpdate(String sql,Object...args){
        int result=0;
        getConnection();

        try {
            ps=con.prepareStatement(sql);
            for (int i=0;i<args.length;i++){
                ps.setObject(i+1,args[i]);
            }
            result=ps.executeUpdate();
        } catch (SQLException e) {
           e.printStackTrace();
        }
      return result;
    }
    public ResultSet excuteQuery(String sql,Object...args){
        getConnection();
        rs=null;
        try {
            ps=con.prepareStatement(sql);
            for(int i=0;i<args.length;i++){
                ps.setObject(i+1,args[i]);
            }
            rs=ps.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }


        return rs;
    }
    public void closeAll(){


            try {  if (rs!=null){
                rs.close();
            }
                if (ps!=null){
                ps.close();}if (con!=null){
                    ps.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

}
